
class Node {
    constructor(element) {
        this.element = element;
        this.next = null;
    }
}

class LinkedList {
    constructor() {
        this.length = 0;
        this.head = null;
    }

    getElementAt(position) {
        if (position < 0 || position >= this.length) {
            return null;
        }
        let current = this.head;
        for (let i = 0; i < position; i++) {
            current = current.next;
        }
        return current;
    }

    append(element) {
        const node = new Node(element);
        let current;
        if (this.head === null) {
            this.head = node;
        } else {
            current = this.head;
            //方案一
            // while (current.next !== null) {
            //     current = current.next;
            // }
            // current.next = node;

            //方案二
            current = this.getElementAt(this.length - 1);
            current.next = node;
        }
        this.length++;
    }

    insert(position, element) {
        if (position >= 0 && position <= this.length) {
            const node = new Node(element);
            let current, previous;
            if (position === 0) {
                node.next = this.head;
                this.head = node;
            } else {
                current = this.getElementAt(position - 1);
                previous = current.next;
                node.next = previous;
                current.next = node;
            }
            this.length++;
            return true;
        }
    }
    
    removeAt(position) {
        if (position >= 0 && position < this.length) {
            let current, previous;
            if (position === 0) {
                this.head = this.head.next;
            } else {
                current = this.getElementAt(position);
                previous = this.getElementAt(position - 1);
                previous.next = current.next;
            }
            this.length--;
            return true;
        }
    }

    indexOf(element) {
        let current = this.head;
        for (let i = 0; i < this.length; i++) {
            if (current.element === element) {
                return i;
            }
            current = current.next;
        }
        return -1;
    }

}    
    